package com.fingard.dsp.bank.directbank.wjzf02;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.directbank.wjzf02.hessian.CCPMDownloadClient;
import com.fingard.dsp.bank.directbank.wjzf02.hessian.CCPMUploadClient;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.text.StringHelper;
import com.fingard.xml.XmlTextReader;

import cacps.DownloadFileService;
import cacps.UploadFileService;

public class WJZF02BatPayRec extends WJZF02Base implements IBatPayRec {
	public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
		return d_BatPayRec(p_req1988);
	}

	public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
		return d_BatPayRec(p_req9188);
	}
	
	public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
		return d_QryBatPayRec(p_req1998);
	}

	public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
		return d_QryBatPayRec(p_req9198);
	}

	public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
		RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqBat.ownAct, "");
			String feeNO = getBankConfig().getMapValueByKey("feeNO" + p_reqBat.reqHeader.transType, p_reqBat.useType);
			boolean isChecked = true;
			String chkMsg = "";
			if (actItem == null) {
				isChecked = false;
				chkMsg = "未找到账号" + p_reqBat.ownAct + "的配置";
			}
			if (StringHelper.isNullOrEmpty(feeNO)) {
				isChecked = false;
				if (chkMsg.length() > 0) {
					chkMsg = chkMsg + "；";
				}
				chkMsg = "未找到代收费项代码";
			}
			if (!isChecked) {
				retAts.respCode = "0";
				retAts.respInfo = chkMsg;
				retAts.reqSeqID = p_reqBat.reqBatchNO;
				retAts.transState = PaymentState.FAIL_Batch;
				retAts.payInfoCode = "E9981";
				retAts.writeRetToATS();
				return retAts;
			}
			
			StringBuilder tmpSbData = new StringBuilder();
			
			String ownAct = p_reqBat.ownAct;
			if(StringHelper.hasAnyChar(actItem.actMapped)){
				ownAct = actItem.actMapped;
			}
			
			String transCode = "";
			if (p_reqBat.reqHeader.transType.equals("1988")) {
				transCode = "40501";
			} else if (p_reqBat.reqHeader.transType.equals("9188")) {
				transCode = "40502";
			}
			boolean isCommonVer = false;
			WriteBankLogLn("batVersion:" + getBankConfig().getValueAsString("batVersion"));
			if(getBankConfig().getValueAsString("batVersion").toLowerCase().equals("common")){
				isCommonVer = true;
			}
			boolean aFlag = getBankConfig().getValueAsBool("isAFlag");
			if(isCommonVer) {
				//通用版本
				//--业务类型|企业编码|费项代码|总笔数|总金额|开户行号|账号|批次序号|
				tmpSbData.append(transCode+"|"+actItem.corpCode+"|"+feeNO+"|"+p_reqBat.totalNum+"|"+p_reqBat.totalAmt+"|"+actItem.cnapsCode+"|"+ownAct+"|"+p_reqBat.reqBatchNO+"|\r\n");
			} else {
				if (aFlag) {
					// A格式//业务类型|企业编码|费项代码|总笔数|总金额|开户行号|账号|批次序号|
					tmpSbData.append(transCode+"|"+actItem.corpCode+"|"+feeNO+"|"+p_reqBat.totalNum+"|"+p_reqBat.totalAmt+"|"+actItem.cnapsCode+"|"+ownAct+"|"+p_reqBat.reqBatchNO+"|\r\n");
				} else {
					// 安邦专用//代收付标识|企业代码|费项代码|业务日期|汇总笔数|汇总金额|企业秸民|企业账号|批次序号|汇总备注|
					Date tmpDateNow = new Date();
					tmpSbData.append(transCode + "|" + actItem.corpCode + "|" + feeNO
							+ "|" + Format.Date8Format.format(tmpDateNow) + "|"
							+ p_reqBat.totalNum + "|" + p_reqBat.totalAmt + "|"
							+ actItem.cnapsCode + "|" + ownAct + "|"
							+ p_reqBat.reqBatchNO + "|" + p_reqBat.abstractATS
							+ "|\r\n");
				}
			}
			
			int tmpCount = 0;
			boolean setBatCnapsByBankName = this.getBankConfig().getValueAsBool("setBatCnapsByBankName");
			while (p_reqBat.readRecord()) {
				tmpCount++;
				tmpSbData.append(tmpCount + "|");
				tmpSbData.append(p_reqBat.readedDetail.cnapsCode + "|");
				if(setBatCnapsByBankName) {
					tmpSbData.append(p_reqBat.readedDetail.getOppBankName()+ "|");
				} else {
				    tmpSbData.append(p_reqBat.readedDetail.getOppBankLocation()+ "|");
				}

				if (p_reqBat.reqHeader.transType.equals("1988")) {
					tmpSbData.append(p_reqBat.readedDetail.recAct + "|");
					tmpSbData.append(p_reqBat.readedDetail.recName + "|");
				} else if (p_reqBat.reqHeader.transType.equals("9188")) {
					tmpSbData.append(p_reqBat.readedDetail.payAct + "|");
					tmpSbData.append(p_reqBat.readedDetail.payName + "|");
				}
				
				tmpSbData.append(p_reqBat.readedDetail.payAmount + "|");
				//代付--明细序号|行号|行名|对方账号|户名|金额(元)|备注|手机号|流水号|省份|城市|分支机构|
				if (p_reqBat.reqHeader.transType.equals("9188")) {
					tmpSbData.append("|");//代扣--协议
				}
				tmpSbData.append(p_reqBat.readedDetail.getUseTypeAndPurpose("+") + "|");
				tmpSbData.append("|");
				tmpSbData.append(p_reqBat.readedDetail.askNumber + "|");
				
				if(isCommonVer) {
					//通用代扣--明细序号|行号|行名|对方账号|户名|金额(元)|协议|备注|手机号|流水号|省份|城市|分支机构|
					String[] pc = p_reqBat.readedDetail.getOppProvinceAndCity2();
					tmpSbData.append(pc[0] + "|");//省份
					tmpSbData.append(pc[1] + "|");//城市
					tmpSbData.append("|");
				} else {
					if (aFlag) { //A格式
						String[] pc = p_reqBat.readedDetail.getOppProvinceAndCity2();
						if (p_reqBat.reqHeader.transType.equals("9188")) {
							tmpSbData.append(p_reqBat.readedDetail.abstractATS + "|");
							tmpSbData.append(p_reqBat.readedDetail.payBankName + "|");
							tmpSbData.append(pc[0] + "|");//省份
							tmpSbData.append(pc[1] + "|");//城市
						} else {
							tmpSbData.append(pc[0] + "|");//省份
							tmpSbData.append(pc[1] + "|");//城市
							tmpSbData.append("|");//省份
							tmpSbData.append(p_reqBat.readedDetail.abstractATS + "|");
							tmpSbData.append(p_reqBat.readedDetail.recBankName + "|");
							
						}
					} else {
						// 安邦专用// 明细序号|明细行号|明细行名（可为空）|明细账号|明细户名|明细金额|明细协议|备注|手机号|流水号|其他|
						tmpSbData.append(p_reqBat.readedDetail.abstractATS + "|");// 其他
					}
				}
				tmpSbData.append("\r\n");
			}
			String sourceFileName = p_reqBat.reqBatchNO + ".txt";
			CCPMUploadClient cupload = new CCPMUploadClient();
			UploadFileService tmpService = cupload.getUploadFileService(bankFront.serverUpload);
			String charset = getCharset();
			WriteBankLogStep2("charset：" + charset);
			WriteBankLogStep2(tmpSbData.toString());
			String tmpBankRet = tmpService.uploadFileDirectXML(sourceFileName,
					actItem.userCode, actItem.userFlag, actItem.corpCode,
					feeNO, transCode, tmpSbData.toString().getBytes(charset),
					actItem.actMapped);
			WriteBankLogStep3(tmpBankRet);
			StringBuilder tmpSbMsg = new StringBuilder();
			XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpBankRet, tmpSbMsg);
			if (tmpBkReader != null) {
				retAts.respCode = "0";
				retAts.reqSeqID = p_reqBat.reqBatchNO;
				String uploadSuccess = tmpBkReader.getSimpleText("UploadSuccess");
				retAts.transState = "NOCFCA+" + uploadSuccess;
				retAts.payInfoCode = uploadSuccess;
				if (uploadSuccess.equals("true")) {
					retAts.respInfo = "上传成功，支付处理中";
				} else {
					retAts.respInfo = tmpBkReader.getSimpleText("SumError");
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = tmpSbMsg.toString();
			}

		} catch (Exception e) {
			retAts.respCode = "-1";
			retAts.respInfo = e.toString();
			e.printStackTrace();
		}
		if (retAts.respCode.equals("-1")
				&& StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
			retAts.reqSeqID = p_reqBat.reqBatchNO;
		}
		retAts.writeRetToATS();
		return retAts;
	}

	public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
		RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);

		ActSetItem actItem = getBankConfig().getActSetItem(p_reqQryBat.ownAct, "");
		String transTypeOri = "";
		if (p_reqQryBat.reqHeader.transType.equals("1998")) {
			transTypeOri = "1988";
		} else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
			transTypeOri = "9188";
		}
		String feeNO = getBankConfig().getMapValueByKey("feeNO" + transTypeOri,	p_reqQryBat.useType);
		boolean isChecked = true;
		String chkMsg = "";
		if (actItem == null) {
			isChecked = false;
			chkMsg = "未找到账号" + p_reqQryBat.ownAct + "的配置";
		}
		if (StringHelper.isNullOrEmpty(feeNO)) {
			isChecked = false;
			if (chkMsg.length() > 0) {
				chkMsg = chkMsg + "；";
			}
			chkMsg = "未找到代收费项代码";
		}
		if (!isChecked) {
			retAts.respCode = "-1";
			retAts.respInfo = chkMsg;
			retAts.reqSeqID = p_reqQryBat.reqBatchNO;
			retAts.writeBeforeDetail();
			retAts.writeAfterDetail();
			return retAts;
		}

		try {
			WriteBankLogStep2("queryCnTrBatchByPropertiesXML(" + actItem.corpCode + ", " + p_reqQryBat.reqBatchNO + ".txt" + ", " + actItem.userCode + ")");
			CCPMDownloadClient cdownload = new CCPMDownloadClient();
			DownloadFileService tmpService = cdownload.getDownloadFileService(bankFront.serverDownload);
			String retQryBatXml = tmpService.queryCnTrBatchByPropertiesXML(actItem.corpCode, p_reqQryBat.reqBatchNO + ".txt", actItem.userCode, "");
			WriteBankLogStep3(retQryBatXml);
			if (StringHelper.hasAnyChar(retQryBatXml)) {
				StringBuilder tmpMsgBat = new StringBuilder();
				XmlTextReader tmpReaderBat = loadBankRespXmlReader(retQryBatXml, tmpMsgBat);
				if (tmpReaderBat != null) {
					/*
					 * <?xml version="1.0" encoding="GBK"?>

					<Message>
					<BatchStatus>900</BatchStatus>
					<BatchNo>2018050811001107003881</BatchNo>
					</Message>
					*/
					String realBatNO = tmpReaderBat.getSimpleText("BatchNo");
					String tmpBatchStatus = tmpReaderBat.getSimpleText("BatchStatus");
					if (StringHelper.hasAnyChar(realBatNO) && tmpBatchStatus.equals("1200")) {
						retAts.respCode = "0";
						retAts.reqSeqID = p_reqQryBat.reqBatchNO;
						WriteBankLogStep2("carryBackBatchDirect(" + p_reqQryBat.reqBatchNO + ", " + feeNO + ", " + actItem.corpCode + ")");
						byte[] retBytes = tmpService.carryBackBatchDirect(realBatNO, feeNO, actItem.corpCode);
						if (retBytes != null) {
							String charset = getCharset();
							String tmpBankRet = new String(retBytes, charset);
							WriteBankLogStep3(tmpBankRet);
							if (tmpBankRet != null) {
								String[] resultString = tmpBankRet.split("\r\n");
								String headString = resultString[0].replace("1-{", "");
								// 0是处理中，1是不存在！
								if (headString.trim().equals("1-Not Exist")	|| headString.equals("-1300该批次不存在")) {
									retAts.transState = headString.trim();// "1-Not Exist+查询批次不存在";
									retAts.payInfoCode = headString.trim();// "1-Not Exist";
									retAts.respInfo = "该批次不存在";
									retAts.writeBeforeDetail();
									retAts.writeAfterDetail();
									return retAts;
								} else if (headString.equals("0-Processing\n") || headString.equals("其他")) {
									retAts.transState = "4";
									retAts.payInfoCode = "0-Processing";
									retAts.respInfo = "支付中";
									retAts.writeBeforeDetail();
									retAts.writeAfterDetail();
									return retAts;
								} else {
									retAts.transState = "2";
									retAts.payInfoCode = "000000";
									retAts.respInfo = "获取文件成功";
								}
								retAts.writeBeforeDetail();

								for (int i = 1; i <= resultString.length - 1; i++) {
									RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();

									String bodyString = resultString[i].replace("{", "").replace(" ", "");
									String[] BodyString = bodyString.split("\\|");
									String OppositeAccountNo = BodyString[3];// 收款账户
									String OppositeAccountName = BodyString[4];// 户名
									String Money = BodyString[5];// 金额（元）
									String Status = BodyString[6];// 回执状态
									String Memo = BodyString[7];// 回执描述
									String Postscript = BodyString[8];// 企业流水号
									if (p_reqQryBat.reqHeader.transType.equals("1998")) {
										tmpRetDetail.recAct = OppositeAccountNo;
										tmpRetDetail.recName = OppositeAccountName;
										tmpRetDetail.payAmount = Money;
										tmpRetDetail.result = Status;
										tmpRetDetail.memo = Memo;
										tmpRetDetail.postScript = Postscript;
										tmpRetDetail.payInfoCode = Status;
									} else if (p_reqQryBat.reqHeader.transType.equals("9198")) {
										tmpRetDetail.payAct = OppositeAccountNo;
										tmpRetDetail.payName = OppositeAccountName;
										tmpRetDetail.payAmount = Money;
										tmpRetDetail.result = Status;
										tmpRetDetail.memo = Memo;
										tmpRetDetail.postScript = Postscript;
										tmpRetDetail.payInfoCode = Status;
									}
									if (Status.equals("90")) {
										tmpRetDetail.payInfoCode = Status + Memo;
									}
									retAts.writeRetDetail(tmpRetDetail);
								}
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = "";
						}
					} else if (tmpBatchStatus.equals("-1300")) {
						retAts.respCode = "0";
						retAts.reqSeqID = p_reqQryBat.reqBatchNO;
						retAts.transState = tmpBatchStatus;
						retAts.respInfo = "该批次不存在";
						retAts.payInfoCode = retAts.transState;
						retAts.writeBeforeDetail();
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = tmpBatchStatus;
					}
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "银行响应内容为空!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			this.WriteBankLogLn(ex);
		}
		if (retAts.respCode.equals("-1") && StringHelper.isNullOrEmpty(retAts.reqSeqID)) {
			retAts.reqSeqID = p_reqQryBat.reqBatchNO;
		}
		if (retAts.respCode.equals("-1")) {
			retAts.writeBeforeDetail();
		}
		
		retAts.writeAfterDetail();
		return retAts;
	}
}
